#!/bin/bash

#
# flashguess -- by Dario Berzano <dario.berzano@gmail.com>
#
# Part of the lfscripts suite -- http://lfscripts.googecode.com/
#
# Tries to guess the path of a currently opened Flash video on OS X.
#

# Main function
function Main() {

  # Find the pattern which occurs the most
  SeriesName=$( find . -type f -maxdepth 1 | sort | while read F ; do

    if [[ $F =~ ^\./(([^-]*)-([0-9]{1,2})x([0-9]{1,2})\.(.{3})) ]] ; then
      File=${BASH_REMATCH[1]}
      Base=${BASH_REMATCH[2]}
      Series=${BASH_REMATCH[3]}
      Episode=${BASH_REMATCH[4]}
      Extension=${BASH_REMATCH[5]}
      echo "${Base}"
    fi

  done | sort | uniq -c | sort -nb | tail -1 | awk '{ print $2 }' )

  if [ "$SeriesName" != '' ] ; then

    # Find the latest episode
    Latest=$( find . -type f -maxdepth 1 -regex "^\./${SeriesName}-[0-9]\{1,2\}x[0-9]\{1,2\}\..\{3\}$" | \
      sort | tail -1 )

    if [[ $Latest =~ ^\./(([^-]*)-([0-9]{1,2})x([0-9]{1,2})\.(.{3})) ]] ; then
      File=${BASH_REMATCH[1]}
      Base=${BASH_REMATCH[2]}
      Series=${BASH_REMATCH[3]}
      Episode=${BASH_REMATCH[4]}
      Extension=${BASH_REMATCH[5]}
      Pattern="${SeriesName}-${Series}x"
      NextEpisode=$Episode
    fi

  fi

  Tmp1=`mktemp /tmp/flashguess-XXXXX`
  Tmp2=`mktemp /tmp/flashguess-XXXXX`

  # Guess Flash paths and sort by timestamp (oldest first)
  lsof -n | egrep -i 'flashtmp|pepper' > $Tmp1
  while read -u 3 Raw ; do
    if [[ "$Raw" =~ (/private.*$) ]] || [[ "$Raw" =~ \ ($HOME.*.com.google.Chrome.*$) ]] ; then
      FlashPath="${BASH_REMATCH[1]}"
      Timestamp=$( stat -f "%SB" -t "%s" "$FlashPath" 2> /dev/null )  # Use %Dz for size in bytes
      [ $? != 0 ] && continue
      echo "$Timestamp $FlashPath"
    fi
  done 3< $Tmp1 | sort -n > $Tmp2 # sort to get the oldest on top!

  # Copy or link?
  if [ "$1" == '--copy' ] ; then
    ActionLabel='Copy'
  elif [ "$1" == '--link' ] ; then
    ActionLabel='Link'
  fi

  # Show and copy
  while read -u 3 Raw ; do

    # Strip timestamp
    FlashPath="${Raw#* }"

    # ls -lh "$FlashPath"
    # file "$FlashPath"

    Type=$( file "$FlashPath" )
    Type=${Type##*:}  # after last colon
    Type=${Type#* }   # after first (initial) space
    Size=$( stat -f "%Dz" "$FlashPath" )  # bytes
    Size=$( echo "scale=1; $Size/1024/1024" | bc )  # MiB
    Timestamp=$( stat -f "%SB" -t "%Y-%m-%d %H:%M:%S" "$FlashPath" )

    # Output
    echo "File: $FlashPath"
    echo "Type: $Type"
    echo "Size: $Size MiB"
    echo "Created: $Timestamp"

    # Does it exist?
    if [ ! -f "$FlashPath" ] ; then
      echo "File is not accessible"
      echo ""
      continue
    fi

    # Suggest name
    if [ "$SeriesName" != '' ] ; then

      # Next episode
      NextEpisode=$( echo "$NextEpisode+1" | bc )
      Suggested=$( printf "${Pattern}%0${#Episode}u." $NextEpisode )  # only ext missing

      # Extension?
      if [[ $Type =~ MPEG[:space:]v4 ]] ; then
        Extension='mp4'
      else
        Extension='flv'
      fi
      Suggested="${Suggested}${Extension}"

    fi

    ffmpeg -i "$FlashPath" 2>&1 | grep -o 'Duration: [0-9:.]\+' 
    if [ "$1" == '--copy' ] || [ "$1" == '--link' ] ; then

      Dest=''

      if [ "$Suggested" != '' ] ; then
        read -n1 -p "$ActionLabel to \"$Suggested\"? [y/n]: " Ans
        echo ''
        [ "$Ans" == 'y' ] || [ "$Ans" == 'Y' ] && Dest="$Suggested"
      fi

      if [ "$Dest" == '' ] ; then
        read -p "$ActionLabel to (leave blank to skip): " Dest
      fi

      if [ "$Dest" != '' ] ; then
        if [ "$1" == '--copy' ] ; then
          cp "$FlashPath" "$Dest"
        else
          ln "$FlashPath" "$Dest"
        fi
        Ret=$?
        if [ $Ret == 0 ] ; then
          echo "$ActionLabel OK"
        else
          echo "$ActionLabel error ($?)"
        fi
      fi
    elif [ "$Suggested" != '' ] ; then
      echo "Suggested name: $Suggested"
    fi

    echo ""

  done 3< $Tmp2
  rm -f $Tmp1 $Tmp2
}

#
# Entry point
#

Main "$@"
